
#include "QDocument.h"


QDocument::QDocument(QObject *parent /* = 0 */)
	: QObject(parent)
	, mFileLocation("")
	, mFileTitle("")
	, mFileExt("")
	, mModifiedFlag(false)
{

}

QDocument::~QDocument()
{
	
}

bool QDocument::create(const QString &filename)
{
	if (filename.isEmpty())
	{
		return false;
	}

	mFile = new QFile(filename);
	if (!mFile->open(QIODevice::ReadWrite))
	{
		delete mFile;
		mFile = 0;
		return false;
	}

	QFileInfo info(filename);
	mFileLocation = info.absolutePath() + "/";
	mFileTitle = info.baseName();
	mFileExt = info.suffix();
	
	bool result = false;

	result = onCreateDocument();

	if (mFile->isOpen())
	{
		mFile->close();
	}	

	delete mFile;
	mFile = 0;

	if (result)
	{
		emit created();
	}

	return result;
}

bool QDocument::open(const QString &filename)
{
	if (filename.isEmpty())
		return false;

	mFile = new QFile(filename);
	if (!mFile->open(QIODevice::ReadOnly))
	{
		delete mFile;
		mFile = 0;
		return false;
	}

	QFileInfo info(filename);
	mFileLocation = info.absolutePath() + "/";
	mFileTitle = info.baseName();
	mFileExt = info.suffix();

	bool result = false;
	result = onOpenDocument();

	if (mFile->isOpen())
	{
		mFile->close();
	}	

	delete mFile;
	mFile = 0;

	if (result)
	{
		emit opened();
	}

	return result;
}

bool QDocument::save(const QString &filename /* = "" */)
{
	QString path;

	if (filename.isEmpty())
	{
		path = mFileLocation + mFileTitle;
		if (!mFileExt.isEmpty())
		{
			path = path + "." + mFileExt;
		}
	}
	else
	{
		path = filename;
	}

	mFile = new QFile(path);
	if (!mFile->open(QIODevice::WriteOnly))
	{
		delete mFile;
		mFile = 0;
		return false;
	}

	bool result = false;
	result = onSaveDocument();

	if (mFile->isOpen())
	{
		mFile->close();
	}	

	delete mFile;
	mFile = 0;

	if (result)
	{
		setModifiedFlag(false);
		emit saved();
	}

	return result;
}

void QDocument::close()
{
	onCloseDocument();
	emit closed();
}

void QDocument::setModifiedFlag(bool flag)
{
	mModifiedFlag = flag;
	emit modified();
}
